package com.szy.douyou_gateway.service.impl;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import com.szy.douyou_gateway.config.ResultDTO;
import com.szy.douyou_gateway.service.FileUploadService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;


/**
 * 文件上传服务
 *
 * @author sunziyan
 * @date 2022/4/2
 */
@Service
public class FileUploadServiceImpl implements FileUploadService {

    /**
     * 腾讯云SecretId
     */
    private static final String SECRET_ID = "AKIDhEWZMuDH5ey3sSmrhIdjaBWhdJjuqWx8";
    /**
     * 腾讯云SecretKey
     */
    private static final String SECRET_KEY = "zkGXZLr89vRijV2JK6duvgCSTEk00kFU";
    /**
     * 腾讯云存储桶区域
     */
    private static final String REGION_NAME = "ap-guangzhou";
    /**
     * 腾讯云存储桶名
     */
    private static final String BUCKET_NAME = "douyou-1308919931";
    /**
     * 腾讯云存储桶url
     */
    private static final String BASE_URL = "https://douyou-1308919931.cos.ap-guangzhou.myqcloud.com/";
    /**
     * 腾讯云SecretId
     */
    private static ClientConfig clientConfig;
    /**
     * 腾讯云SecretId
     */
    private static COSClient cosClient;

    static {
        COSCredentials cred = new BasicCOSCredentials(SECRET_ID, SECRET_KEY);
        Region region = new Region(REGION_NAME);
        clientConfig = new ClientConfig(region);
        cosClient = new COSClient(cred, clientConfig);
    }


    /**
     * 上传文件到cos
     *
     * @param multipartFile
     * @return
     * @throws IOException
     */
    public String fileUpload(MultipartFile multipartFile) throws IOException {
        File localFile = null;
        String originalFilename = multipartFile.getOriginalFilename();
        String[] filename = originalFilename.split("\\.");
        localFile = File.createTempFile(filename[0], filename[1]);
        multipartFile.transferTo(localFile);
        localFile.deleteOnExit();
        String key = "douyou/images/" + System.currentTimeMillis() + ".png";
        PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET_NAME, key, localFile);
        PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
        return key;
    }


    @Override
    public ResultDTO getImageUploadUrl(MultipartFile multipartFile) {

        String key = null;
        try {
            key = fileUpload(multipartFile);
        } catch (IOException e) {
            return ResultDTO.fail("本地文件转换失败");
        }
        String url = BASE_URL + key;
        return ResultDTO.success(url);
    }


}
